<script setup>
import {nextTick, reactive, ref} from 'vue'
import MyForm from '@/components/MyTable.vue';
import { emailValid, phoneValid } from '@/utils/validator';
import { ElMessage ,ElMessageBox} from 'element-plus';
import { deleteUsers, getUserListApi, modifyUser, registerApi, searchUser, } from '@/api/user';

getUserList(10, 1)
// 表格组件
const multipleTableRef = ref(null)
// 表格数据
const accountInfoList = ref([])
// 弹窗表格组件实例
const dialogFormRef = ref(null)
// 表单label
const labels = [
  {key:'账户名称',value:'accountName'},
  {key:'账户角色',value:'accountRoleText'},
  {key:'电话',value:'phoneNumber'},
  {key:'邮箱',value:'email'},
  {key:'备注',value:'registrationRemark'},
]
// 查询响应式数据
const searchObj = ref({
  "accountName":'',
  "phoneNumber":'',
  "email":''
})
// 弹窗的响应式绑定数据
const dialogForm = ref({
    "accountName": "",
    "accountRole": "",
    "phoneNumber": "",
    "email": "",
    "password":"",
    "registrationRemark": ""
})
// MyForm 组件实例
const MyFormRef = ref(null)
// 用户数据的总数
const userCount = ref(0)
// 弹窗选择账户角色
const accountRoles = reactive([
  {key:1,value:'管理员'},
  {key:2,value:'老师'}
])
// 校验规则具体
const validateField = {
  accountName: (rule, value, callback) => {
    if (!value) {
      callback(new Error('账户名称不能为空'));
    } else if (value.length > 100) {
      callback(new Error('姓名长度过长,请少于100个字符'));
    } else {
      callback();
    }
  },
  phone: (rule, value, callback) => {
    if (!value) {
      callback(new Error('电话号码不能为空'));
    } else if (!phoneValid(value)) {
      callback(new Error('电话号码格式不正确'));
    } else {
      callback();
    }
  },
  email: (rule, value, callback) => {
    if (!value) {
      callback(new Error('邮箱不能为空'));
    } else if (!emailValid(value)) {
      callback(new Error('邮箱格式不正确'));
    } else {
      callback();
    }
  },
  accountRole: (rule, value, callback) => {
    if (!value) {
      callback(new Error('账户角色不能为空'));
    } else if (value != 1 && value != 2) {
      callback(new Error('账户角色无效'));
    } else {
      callback();
    }
  },
  remark: (rule, value, callback) => {
    if (value && value.length > 255) {
      callback(new Error('备注不能超过255个字符'));
    } else {
      callback();
    }
  },
  password:(rule,value,callback) => {
    if (!value) {
      callback(new Error('密码不能为空'));
    } else if (value.length < 8 || value.length > 20) {
      callback(new Error('密码长度必须在 8 到 20 位之间'));
    } else if (/[\u4e00-\u9fa5]/.test(value)) {
      callback(new Error('密码不能包含中文字符'));
    } else {
      const hasLetter = /[a-zA-Z]/.test(value);
      const hasNumber = /[0-9]/.test(value);
      const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(value);

      const validCount = [hasLetter, hasNumber, hasSpecialChar].filter(Boolean).length;
      if (validCount < 2) {
        callback(new Error('密码必须包含字母、数字和特殊字符中的至少两种'));
      } else {
        callback();
      }
    }
  }
};
// 弹窗表单校验规则
const dialogRules = {
  accountName:[
    {required:true,message:'请输入账户名称',trigger:'blur'},
    {validator:validateField.accountName,trigger:'blur'}

  ],
  accountRole:[
    {required:true,message:'请输入电话名称',trigger:'change'},
    {validator:validateField.accountRole,trigger:'blur'}

  ],
  phoneNumber:[
    {required:true,message:'请输入电话',trigger:'blur'},
    {validator:validateField.phone,trigger:'blur'}

  ],
  email:[
    {required:true,message:'请输入邮箱',trigger:'blur'},
    {validator:validateField.email,trigger:'blur'}

  ],
  password:[
    {required:true,message:'请输入密码',trigger:'blur'},
    {validator:validateField.password,trigger:'blur'}
  ]

}
// 弹窗是否可见
const dialogFormVisible = ref(false)

// 弹窗标题
const currentDialogTitles = ref([
  {key:1,value:'修改账户/角色'},
  {key:2,value:'查看账户/角色'},
  {key:3,value:'创建账户/角色'}
])
// 当前弹窗类型
const currentDialogTitleIndex = ref(0)



// 当前选择数据的数目
const selectRows = ref([])

// 清除选择
const clearAllSelection = () => {
  multipleTableRef.value.clearSelection()
}
// 处理点击新增按钮
const handleAdd = () => {
  dialogFormVisible.value = true;
  currentDialogTitleIndex.value = 2;
}

// 选择数目
const handleSelectChange = (selectRows1) => {
  selectRows.value = selectRows1

}

//查看数据
const handleShow = (id) => {
  dialogForm.value = {...accountInfoList.value.find((item) => {return item.id === id})}
  dialogFormVisible.value = true;
  currentDialogTitleIndex.value = 1;
}
// 修改数据
const handleEdit = async (id) => {
  dialogForm.value = {...accountInfoList.value.find((item) => {return item.id === id})}
  dialogFormVisible.value = true;
  currentDialogTitleIndex.value = 0;

}

// 删除数据
const handleDel = (id) => {
  const ids = [id]
  ElMessageBox.confirm('你确定要删除这条数据吗? 注意!此操作不可逆转')
    .then(async() => {
        try{
          await deleteUsers(ids)
          ElMessage.success("删除成功")
          await MyFormRef.value.getDataList()
        }catch(e) {
          ElMessage.error(e.message)
        }
    }).catch(()=>{

    })

}

// 注册用户或者修改用户点击触发
const handleConfirm =  () => {
  dialogFormRef.value.validate(async (valid) => {
    if(!valid) {
      return ElMessage.error('请填写正确的信息')
    }
    if(currentDialogTitleIndex.value == 2) {
    try{
      await registerApi(dialogForm.value)
      ElMessage.success("新增用户成功")
      await MyFormRef.value.getDataList()
      dialogFormVisible.value = false
          handleDialogClose()
    }catch(e) {
      ElMessage.error(e.message)
    }
  }else {
    try{
      await modifyUser(dialogForm.value)
      ElMessage.success("修改成功")
      await MyFormRef.value.getDataList()
      dialogFormVisible.value = false
      handleDialogClose()
    }catch(e) {
      ElMessage.error(e.message)
    }
    }

  })
}
// 得到用户列表
async function getUserList(pageSize,page) {
  try{
    const res = await getUserListApi(pageSize,page)
    accountInfoList.value = res.userList
    userCount.value = res.userCount

  }catch(e) {
    ElMessage.error(e.message);
    // console.log();

  }
}

// 多选删除
const handleDelByIds = () => {
  const ids = []
  selectRows.value.forEach((item) => {
    ids.push(item.id)
  })
  ElMessageBox.confirm('你确定要删除这些数据吗? 注意!此操作不可逆转')
    .then(async() => {
        try{
          await deleteUsers(ids)
          ElMessage.success("删除成功")
          await MyFormRef.value.getDataList()
        }catch(e) {
          ElMessage.error(e.message)
        }
    })

}
// 查询
const handleSearch = async () => {
  if(searchObj.value.accountName === '' && searchObj.value.phoneNumber === '' && searchObj.value.email === '') {
    await MyFormRef.value.getDataList()
    return
  }
  if(searchObj.value.accountName !== '' && searchObj.value.length > 100) {
    ElMessage.warning("账户名称长度过长")
    return
  }
  if(searchObj.value.phoneNumber !== '' && !phoneValid(searchObj.value.phoneNumber)) {
    ElMessage.warning("手机号格式不正确")
    return
  }
  if(searchObj.value.email !== '' && !emailValid(searchObj.value.email)) {
    ElMessage.warning("邮箱格式不正确")
    return
  }
  const res = await searchUser(searchObj.value)
  if(res.length === 0) {
    ElMessage.warning('查不到满足条件的用户')
  }else {
    accountInfoList.value = res
    ElMessage.success('查询成功')
  }

}

// 弹窗关闭前
const handleDialogClose = () => {
  Object.keys(dialogForm.value).forEach(key => {
    dialogForm.value[key] = ''
  })
  dialogForm.value.accountRole = 1
  nextTick(() => {
    dialogFormRef.value.clearValidate()
  })
  dialogFormVisible.value = false
}
</script>

<template>
    <div class="account-container">
      <!-- dialog -->
      <el-dialog v-model="dialogFormVisible" :title="currentDialogTitles[currentDialogTitleIndex].value" width="50%" :before-close="handleDialogClose">
        <el-form :model="dialogForm" :rules="dialogRules" :disabled="currentDialogTitleIndex === 1" ref="dialogFormRef">
          <el-form-item prop="accountName" label="账户名称">
            <el-input v-model="dialogForm.accountName" placeholder="请输入账户名称" autocomplete="off" size="default" style="width: 100%;"/>
          </el-form-item>
          <el-form-item prop="phoneNumber" label="电话">
            <el-input v-model="dialogForm.phoneNumber" autocomplete="off" placeholder="请输入电话" size="default" style="width: 100%;"/>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="dialogForm.email" autocomplete="off" placeholder="请输入邮箱" size="default" style="width: 100%;"/>
          </el-form-item>
          <el-form-item prop="accountRole" label="账户角色">
            <el-select v-model="dialogForm.accountRole" placeholder="请选择账户角色" size="default">
                <el-option v-for="item in accountRoles" :key="item.key" :label="item.value" :value="item.key">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="password" label="密码" v-if="currentDialogTitleIndex === 2">
            <el-input v-model="dialogForm.password" autocomplete="off"
            placeholder="请输入密码"
            size="default"
            style="width: 100%;"
            show-password
            type="password"/>
          </el-form-item>
          <el-form-item prop="registrationRemark" label="备注" style="width:100%">
            <el-input v-model="dialogForm.registrationRemark" type="textarea" size="large" style="width: 100%;" :rows="5"
            maxlength="255" show-word-limit
            placeholder="请输入备注信息"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleDialogClose()" size="default" >取消</el-button>
            <el-button type="primary" @click="handleConfirm" size="default" >
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
      <div class="nav_show">首页/账户/角色管理</div>
      <div class="title">
        <h3>账户/角色管理</h3>
      </div>
      <div class="inp"  style="margin-bottom: 20px;">
        <div class="left">
          <el-button color="#1274b7" size="default"
          @click="handleAdd"
          >新增</el-button>
          <el-button
          :disabled="selectRows.length === 0"
          size="default"
           type="danger"
           @click="clearAllSelection">({{ selectRows.length }})取消选中</el-button>
           <el-button type="danger"  circle size="default" v-show="selectRows.length > 0" @click="handleDelByIds">
            <el-icon><Delete /></el-icon>
           </el-button>
        </div>
        <div class="right">
          <el-form  :model="searchObj" size="default">
            <el-form-item><el-input  placeholder="请输入账户名称" size="default" v-model="searchObj.accountName"></el-input></el-form-item>
            <el-form-item><el-input  placeholder="请输入电话" size="default" v-model="searchObj.phoneNumber"></el-input></el-form-item>
            <el-form-item><el-input  placeholder="请输入邮箱" size="default" v-model="searchObj.email"></el-input></el-form-item>
          </el-form>
          <el-button type="primary" size="default" @click="handleSearch">查询</el-button>
        </div>
      </div>
      <MyForm :data="accountInfoList" :labels="labels"
      @selectChange="handleSelectChange"
       @del="handleDel" @show="handleShow" @edit="handleEdit" @getDataList="getUserList" :dataCount="userCount"
       :op="true" :select="true" ref="MyFormRef" :paging="true"></MyForm>
    </div>
</template>

<style scoped lang="less">
.account-container {
  padding: 20px;
  background-color: #fff;
  .title {
    margin-top: 20px;
    margin-bottom: 20px;
    h3 {
      font-weight: normal;
    }
  }

}

.inp {
  display: flex;
  justify-content: space-between;
  .right {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
  ::v-deep .is-disabled {
    background-color: #f5f5f5;
    border: none;
  }
}

 .el-table {
  margin-top: 20px;
}

::v-deep .el-table__header th{
   color: black;
}

::v-deep .el-table {
  .el-button {
    border: none;
    font-size: 20px;
    background-color: transparent;
  }
}

::v-deep .row-highLight {
  background-color: #e6f4ff !important;
}

::v-deep .no-hover:hover > td {
  background-color: #e6f4ff  !important;
}





// dialog
.el-dialog {
  .el-form  {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  .el-form-item  {
    display: block;
    width: 45%;
  }


}

::v-deep .el-form-item__label {
    font-size: 15px;
    color: black;
  }
::v-deep .el-textarea .el-input__count {
    bottom: -15px;
  }

  // 查询
  .right {
    .el-form{
      display: flex;
    }
  }
</style>
